//引入jbolt 核心 配置
import JBOLT_CONFIG from './jbolt_config.js'; //引入sha1算法库

import sha1 from './sha1.js'; //引入md5算法库

import md5 from './md5.js'; //引入jbolt api 配置表

import JBOLT_API_CONFIG from './jbolt_api.js'; //引入jbolt msg 配置表

import JBOLT_MSG_CONFIG from './jbolt_msg.js';
import jbolt_api from './jbolt_api';
const JBOLT_APIS = JBOLT_API_CONFIG.JBOLT_APIS;
const JBOLT_MSG = JBOLT_MSG_CONFIG.MSG; //当前随机字符串生成使用

const baseNoce = 'abcdefghijklmnqstuwxyz0123456789'; //核心配置

const config = JBOLT_CONFIG.config;
/**
 *jbolt sdk初始化
 */

const init = () => {
    log('2、jbolt init'); //拿到本地JWT

    let jwt = getLocalJwt(); //如果有就设置到核心配置里

    if (jwt) {
        log('3、check has jwt in local,set config.jwt');
        config.jwt = jwt;
    } else {
        //没有就得执行登录
        //根据config配置的跳转类型执行
        if (config.JBOLT_GOTOLOGIN_TYPE == 1) {
            log('3、check no jwt，need wx.login'); //执行微信login

            WxLoginUtil.login();
        } else if (config.JBOLT_GOTOLOGIN_TYPE == 2) {
            log('3、check no jwt，need redirec to login page'); //跳转到登录页面 具体登录页面地址在config里配置

            redirecToPage(config.JBOLT_GOTOLOGIN_PAGE_URL);
        }
    }
};
/**
 * 判断是否登录
 */

const isLogined = () => {
    return config.jwt != null && config.jwt.length > 50 && config.refreshJwt != null && config.refreshJwt.length > 50;
};
/**
 * 创建随机字符
 */

const createNoce = (length) => {
    let sb = new Array();
    let max = baseNoce.length - 1;

    for (let i = 0; i < length; i++) {
        sb.push(baseNoce.charAt(random(0, max)));
    }

    return sb.join('');
};
/**
 * 处理密码明文转加密
 * @param {*} pwd
 */

const processPwd = (pwd) => {
    let left = createNoce(2);
    let right = createNoce(3);
    return left + md5(pwd) + right;
};
/**
 * 产生随机整数，包含下限值，包括上限值
 * @param {Number} lower 下限
 * @param {Number} upper 上限
 * @return {Number} 返回在下限到上限之间的一个随机整数
 */

const random = (lower, upper) => {
    return Math.floor(Math.random() * (upper - lower + 1)) + lower;
};
/**
 * 创建jbolt_jwt_sign
 * @param {*} isRefreshJwt 是否加密的是refreshJwt
 */

const createSignature = (isRefreshJwt) => {
    let timestamp = new Date().getTime() + '';
    let nonce = createNoce(8);
    let token = isRefreshJwt ? config.refreshJwt : config.jwt;
    let arr = [token, timestamp, nonce];
    let result = arr.sort().join('');
    var signature = sha1(result);
    return {
        signature: signature,
        timestamp: timestamp,
        nonce: nonce
    };
};
/**
 * 获取当前JBolt应用开发中心分配的APPID
 */

const getAppId = () => {
    return config.APPID;
};
/**
 * 获取本地存储的JWT
 */

const getLocalJwt = () => {
    return uni.getStorageSync(config.JBOLT_JWT_KEY);
};
/**
 * 获取本地存储的refresh JWT
 */

const getLocalRefreshJwt = () => {
    return uni.getStorageSync(config.JBOLT_REFRESH_JWT_KEY);
};
/**
 * 更新本地JWT
 */

const updateJwt = (jwt) => {
    log('更新JWT:');
    config.jwt = jwt;
    uni.setStorageSync(config.JBOLT_JWT_KEY, jwt);
};
/**
 * 更新本地refresh JWT
 */

const updateRefreshJwt = (refreshJwt) => {
    log('更新refresh JWT:');
    config.refreshJwt = refreshJwt;
    uni.setStorageSync(config.JBOLT_REFRESH_JWT_KEY, refreshJwt);
};
/**
 * 清空JWT
 */

const clearJwt = () => {
    config.jwt = null;
    uni.removeStorageSync(config.JBOLT_JWT_KEY);
};
/**
 * 清空refresh JWT
 */

const clearRefreshJwt = () => {
    config.refreshJwt = null;
    uni.removeStorageSync(config.JBOLT_REFRESH_JWT_KEY);
};
/**
 * reload 本地JWT
 */

const reloadLocalJwt = () => {
    let jwt = getLocalJwt();

    if (jwt) {
        config.jwt = jwt;
    }
};
/**
 * reload 本地refresh JWT
 */

const reloadLocalRefreshJwt = () => {
    let refreshJwt = getLocalRefreshJwt();

    if (refreshJwt) {
        config.refreshJwt = refreshJwt;
    }
};
/**
 * 日志输出
 */

const log = (info) => {
    if (config.DEV_MODE) {
        console.log(info);
    }
};
/**
 * 时间格式化
 */

const formatTime = (date) => {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();
    const second = date.getSeconds();
    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':');
};

const formatNumber = (n) => {
    n = n.toString();
    return n[1] ? n : '0' + n;
};
/**
 * 根据具体的错误代码和msg 判断 客户端显示信息
 */

const processByErrorCode = (res, req, resolve, reject) => {
    if (res.code) {
        if (res.code == 4030) {
            //refreshjwt也过期了
            if (config.JBOLT_GOTOLOGIN_TYPE == 1) {
                WxLoginUtil.login().then(
                    (res) => {
                        if (resolve) {
                            resolve(res);
                        }
                    },
                    (err) => {
                        if (reject) {
                            reject(err);
                        }
                    }
                );
            } else if (config.JBOLT_GOTOLOGIN_TYPE == 2) {
                //跳转到登录页面 具体登录页面地址在config里配置
                redirecToPage(config.JBOLT_GOTOLOGIN_PAGE_URL);
            }

            return;
        }

        if (res.code == 4005 || res.code == 4004) {
            //JWT过期处理
            if (config.JBOLT_GOTOLOGIN_TYPE == 1) {
                if (config.REFRESH_JWT_TYPE == 'wxlogin') {
                    WxLoginUtil.login().then((res) => {
                        createApiRequest(req)
                            .send()
                            .then(
                                (res) => {
                                    if (resolve) {
                                        resolve(res);
                                    }
                                },
                                (err) => {
                                    if (reject) {
                                        reject(err);
                                    }
                                }
                            );
                    });
                } else if (config.REFRESH_JWT_TYPE == 'api') {
                    JwtRefreshUtil.refresh().then((res) => {
                        createApiRequest(req)
                            .send()
                            .then(
                                (res) => {
                                    if (resolve) {
                                        resolve(res);
                                    }
                                },
                                (err) => {
                                    if (reject) {
                                        reject(err);
                                    }
                                }
                            );
                    });
                }
            } else if (config.JBOLT_GOTOLOGIN_TYPE == 2) {
                //跳转到登录页面 具体登录页面地址在config里配置
                redirecToPage(config.JBOLT_GOTOLOGIN_PAGE_URL);
            }

            return;
        }

        if (res.code == 4000) {
            MsgBox.alert(JBOLT_MSG.byCode[res.code.toString()] + (res.msg ? ',' + res.msg : '系统异常[' + res.code.toString() + ']'));
        } else {
            MsgBox.error(JBOLT_MSG.byCode[res.code.toString()] || (res.msg ? res.msg : '系统异常[' + res.code.toString() + ']'), 2000);
        }

        if (reject) {
            reject(res);
        }
    }
};
/**
 * get调用API
 */

const apiGet = (req) => {
    req.method = 'GET';
    req.isUploadFile = false;
    return createApiRequest(req).send();
};
/**
 * post调用API
 */

const apiPost = (req) => {
    req.method = 'POST';
    req.isUploadFile = false;
    return createApiRequest(req).send();
};
/**
 * post调用API 提交json Raw
 */

const apiPostJson = (req) => {
    if (!req.header) {
        req.header = {};
    }

    req.header['Content-Type'] = 'application/json';
    return apiPost(req);
};
/**
 * 上传文件
 */

const uploadFile = (req) => {
    if (!req || !req.file) {
        MsgBox.error('请选择文件后执行上传', 1000);
        return false;
    }

    return createUploadFileRequest(req).send();
};
/**
 * delete调用API
 */

const apiDelete = (req) => {
    req.method = 'DELETE';
    req.isUploadFile = false;
    return createApiRequest(req).send();
};
/**
 * put调用API
 */

const apiPut = (req) => {
    req.method = 'PUT';
    req.isUploadFile = false;
    return createApiRequest(req).send();
};
/**
 * 处理一下request的header
 */

const processApiRequest = (req) => {
    if (!req.header) {
        req.header = {};
    }

    req.header[config.JBOLT_APPID_KEY] = config.APPID;
    req.header[config.JBOLT_API_REQUEST] = 'true';

    if (!req.isUploadFile) {
        //默认get
        if (!req.method) {
            req.method = 'GET';
        } //处理显示声明 content-type

        if (!req.header['Content-Type']) {
            if (req.method == 'POST') {
                req.header['Content-Type'] = 'application/x-www-form-urlencoded';
            } else {
                req.header['Content-Type'] = 'application/json';
            }
        }
    }

    let withJwt = true; //默认需要jwt

    let withRefreshJwt = false; //默认不需要refreshjwt

    if (typeof req.url == 'object') {
        withJwt = req.url.withJwt;
        withRefreshJwt = req.url.withRefreshJwt;
        req.apiUrl = getApiUrl(req.url.url);
    } else {
        req.apiUrl = getApiUrl(req.url);
    } //请求需要jwt 才设置jwt

    if (withJwt && !withRefreshJwt) {
        //有的页面是经过JBolt.init()的 有的分享出去的页面可能没有
        //这里先判断是否有JWT了 如果config里没有 就再去本地存储找找
        let userIsLogined = isLogined();

        if (!userIsLogined) {
            reloadLocalJwt();
            reloadLocalRefreshJwt();
            userIsLogined = isLogined();
        } //如果已经在config里的就可以直接使用了

        if (userIsLogined) {
            //从本地存储里拿到jwt
            req.header[config.JBOLT_JWT_KEY] = config.jwt;

            if (config.JBOLT_JWT_CHECKSIGN) {
                let jbsign = createSignature(false);
                req.header[config.JBOLT_JWT_SIGNATURE_KEY] = jbsign.signature;
                req.header[config.JBOLT_JWT_TIMESTAMP_KEY] = jbsign.timestamp;
                req.header[config.JBOLT_JWT_NONCE_KEY] = jbsign.nonce;
            }
        } else {
            return false;
        }
    } //请求需要refresh jwt 才设置refresh jwt

    if (withRefreshJwt && !withJwt) {
        //这里先判断是否有JWT了 如果config里没有 就再去本地存储找找
        let userIsLogined = isLogined();

        if (!userIsLogined) {
            reloadLocalJwt();
            reloadLocalRefreshJwt();
            userIsLogined = isLogined();
        } //如果已经在config里的就可以直接使用了

        if (userIsLogined) {
            //从本地存储里拿到jwt
            req.header[config.JBOLT_REFRESH_JWT_KEY] = config.refreshJwt;

            if (config.JBOLT_JWT_CHECKSIGN) {
                let jbsign = createSignature(true);
                req.header[config.JBOLT_JWT_SIGNATURE_KEY] = jbsign.signature;
                req.header[config.JBOLT_JWT_TIMESTAMP_KEY] = jbsign.timestamp;
                req.header[config.JBOLT_JWT_NONCE_KEY] = jbsign.nonce;
            }
        } else {
            return false;
        }
    }

    return true;
};
/**
 * 封装API调用
 */

const createApiRequest = (req) => {
    if (req.isUploadFile) {
        return createUploadFileRequest(req);
    }

    let p = null; //处理一下req的header method 包括jwt和checksign信息

    let reqsuccess = processApiRequest(req);

    if (reqsuccess) {
        log('4、api request start=='); //构建一个请求

        let apiRequest = {
            url: req.apiUrl,
            method: req.method,
            header: req.header,
            data: req.data
        }; //创建Promise

        p = new Promise((resolve, reject) => {
            //执行API访问请求
            //是否需要loading
            if (req.loading) {
                if (typeof req.loading == 'boolean') {
                    MsgBox.loading();
                } else {
                    MsgBox.loading(req.loading);
                }
            }

            if (config.DEV_MODE) {
                log('======JBolt Api Report======');
                log('time:' + formatTime(new Date()));
                log('url:' + req.apiUrl);
                log('data:');
                log(req.data || '--nothing--');
                log('========JBolt Api Request Send...======');
            } //调用wx自身API 发起请求

            uni.request(
                Object.assign(
                    {
                        success: function (res) {
                            let resHeader = res.header;
                            let resData = res.data;

                            if (config.DEV_MODE) {
                                log('======JBolt Api Result======');
                                log(resData || '--nothing--');
                            } //隐藏loading

                            MsgBox.hideLoading(); //设置保存TOken到本地

                            if (resData && resData.state == 'ok') {
                                //不处理预检信息
                                if (resData.data && resData.data['OPTIONS'] == 1) {
                                    log('======OPTIONS SUCCESS======');
                                    return false;
                                } //如果有jwt返回

                                let jwt = resHeader[config.JBOLT_JWT_KEY];

                                if (jwt) {
                                    updateJwt(jwt);
                                } //如果有refresh jwt返回

                                let refreshJwt = resHeader[config.JBOLT_REFRESH_JWT_KEY];

                                if (refreshJwt) {
                                    updateRefreshJwt(refreshJwt);
                                } //成功回调

                                if (resolve) {
                                    resolve(resData);
                                }
                            } else {
                                processByErrorCode(resData, req, resolve, reject);
                            }
                        },
                        error: function (e) {
                            MsgBox.error('网络错误', 1000, reject);
                        },
                        fail: function (e) {
                            MsgBox.error('网络错误', 1000, reject);
                        }
                    },
                    apiRequest
                )
            );
        });
    } else {
        //根据config配置的跳转类型执行
        if (config.JBOLT_GOTOLOGIN_TYPE == 1) {
            if (config.REFRESH_JWT_TYPE == 'wxlogin') {
                log('4、api request no jwt, need wx.login');
                p = WxLoginUtil.login();
            } else if (config.REFRESH_JWT_TYPE == 'api') {
                log('4、api request no jwt, need refresh jwt');
                p = JwtRefreshUtil.refresh();
            } //执行

            p.then(() => {
                return createApiRequest(req).send();
            });
        } else if (config.JBOLT_GOTOLOGIN_TYPE == 2) {
            log('4、api request no jwt, need redirec to login Page'); //跳转到登录页面 具体登录页面地址在config里配置

            redirecToPage(config.JBOLT_GOTOLOGIN_PAGE_URL);
            return;
        }
    }

    return {
        //默认已经调用了请求，这里使用send()返回Promise 留待后续封装调用
        send: () => p
    };
};
/**
 * 封装上传调用
 */

const createUploadFileRequest = (req) => {
    req.isUploadFile = true;
    let p = null; //处理一下req的header method 包括jwt和checksign信息

    let reqsuccess = processApiRequest(req);

    if (reqsuccess) {
        log('4、api request start=='); //构建一个请求

        let apiRequest = {
            filePath: req.file,
            name: req.name || 'file',
            url: req.apiUrl,
            header: req.header,
            formData: req.data
        }; //创建Promise

        p = new Promise((resolve, reject) => {
            //执行API访问请求
            //是否需要loading
            if (req.loading) {
                if (typeof req.loading == 'boolean') {
                    MsgBox.loading('上传中...');
                } else {
                    MsgBox.loading(req.loading ? req.loading : '上传中...');
                }
            }

            if (config.DEV_MODE) {
                log('======JBolt Upload File Report======');
                log('time:' + formatTime(new Date()));
                log('url:' + req.apiUrl);
                log('file:' + req.file);
                log('data:');
                log(req.data || '--nothing--');
                log('========JBolt Upload File Request Send...======');
            }

            uni.uploadFile(
                Object.assign(
                    {
                        success: function (res) {
                            log('==上传success调用==');
                            let resHeader = res.header;
                            var resStr = res.data;

                            if (config.DEV_MODE) {
                                log('======JBolt Upload File Result======');
                                log(resStr || '--nothing--');
                            } //隐藏loading

                            MsgBox.hideLoading();

                            if (resStr) {
                                var resData = JSON.parse(resStr); //设置保存TOken到本地

                                if (resData && resData.state == 'ok') {
                                    //不处理预检信息
                                    if (resData.data && resData.data['OPTIONS'] == 1) {
                                        log('======OPTIONS SUCCESS======');
                                        return false;
                                    } //如果有jwt返回

                                    let jwt = resHeader[config.JBOLT_JWT_KEY];

                                    if (jwt) {
                                        updateJwt(jwt);
                                    }

                                    if (req.noMsg || req.successNoMsg) {
                                        //成功回调
                                        if (resolve) {
                                            resolve(resData);
                                        }
                                    } else {
                                        MsgBox.success('上传成功', 500, function () {
                                            //成功回调
                                            if (resolve) {
                                                resolve(resData);
                                            }
                                        });
                                    }
                                } else {
                                    processByErrorCode(resData, req, resolve, reject);
                                }
                            }
                        },
                        fail: function () {
                            MsgBox.error('网络错误', 1000, reject);
                        }
                    },
                    apiRequest
                )
            );
        });
    } else {
        //根据config配置的跳转类型执行
        if (config.JBOLT_GOTOLOGIN_TYPE == 1) {
            if (config.REFRESH_JWT_TYPE == 'wxlogin') {
                log('4、upload File request no jwt, need wx.login');
                p = WxLoginUtil.login();
            } else if (config.REFRESH_JWT_TYPE == 'api') {
                log('4、upload File request no jwt, need refresh jwt');
                p = JwtRefreshUtil.refresh();
            } //执行

            p.then(() => {
                return createUploadFileRequest(req).send();
            });
        } else if (config.JBOLT_GOTOLOGIN_TYPE == 2) {
            log('4、upload File request no jwt, need redirec to login Page'); //跳转到登录页面 具体登录页面地址在config里配置

            redirecToPage(config.JBOLT_GOTOLOGIN_PAGE_URL);
            return;
        }
    }

    return {
        //默认已经调用了请求，这里使用send()返回Promise 留待后续封装调用
        send: () => p
    };
};
/**
 * 拼接API完整地址
 */

const getApiUrl = (url) => {
    if (url.indexOf('http://') == -1 && url.indexOf('https://') == -1) {
        if (url.charAt(0) != '/') {
            url = config.API_HOST + '/' + url;
        } else {
            url = config.API_HOST + url;
        }
    }

    return url;
};
/**
 * 信息框
 */

const MsgBox = {
    success: function (msg, time, handler) {
        time = time || 1000;
        msg = msg || '操作成功';
        uni.showToast({
            title: msg,
            icon: 'success',
            duration: time,
            success: function () {
                log('success:' + msg);

                if (handler) {
                    handler();
                }
            }
        });
    },
    info: function (msg, time, handler) {
        time = time || 1000;
        msg = msg || 'OK';
        uni.showToast({
            title: msg,
            icon: 'none',
            duration: time,
            success: function () {
                log('success:' + msg);

                if (handler) {
                    handler();
                }
            }
        });
    },
    loading: function (msg, time, handler) {
        time = time || 10000;
        msg = msg || '加载中';
        uni.showLoading({
            title: msg
        });
        setTimeout(() => {
            uni.hideLoading();

            if (handler) {
                handler();
            }
        }, time);
    },
    hideLoading: function (time) {
        if (time) {
            setTimeout(() => {
                uni.hideLoading();
            }, time);
        } else {
            uni.hideLoading();
        }
    },
    error: function (msg, time, handler) {
        time = time || 1000;
        msg = msg || '错误';
        uni.showToast({
            title: msg,
            icon: 'none',
            duration: time,
            success: function () {
                log('error:' + msg);

                if (handler) {
                    handler();
                }
            }
        });
    },
    alert: function (content, okHandler) {
        uni.showModal({
            title: '提示',
            content: content,
            showCancel: false,

            success(res) {
                if (res.confirm) {
                    if (okHandler) {
                        okHandler();
                    }

                    log('用户点击确定');
                }
            }
        });
    },
    confirm: function (content, okHandler, cancelHandler) {
        uni.showModal({
            title: '请确认',
            content: content,
            confirmText: '确定',
            cancelText: '取消',
            success: function (res) {
                if (res.confirm) {
                    if (okHandler) {
                        okHandler();
                    }

                    log('用户点击确定');
                } else {
                    if (cancelHandler) {
                        cancelHandler();
                    }

                    log('用户点击取消');
                }
            }
        });
    }
};
/**
 * 打开指定page
 */

const openPage = (pageUrl, param, callback, events) => {
    if (param) {
        pageUrl = pageUrl + '?' + jsonToUrlParams(param);
    }

    uni.navigateTo({
        url: pageUrl,
        events: events,
        success: callback ? callback(true) : undefined,
        fail: callback ? callback(false) : undefined
    });
};
/**
 * json对象转URL 参数
 */

const jsonToUrlParams = (json) => {
    if (!json || json.length == 0) {
        return '';
    }

    let tempArr = [];

    for (var i in json) {
        var key = encodeURIComponent(i);
        var value = encodeURIComponent(json[i]);
        tempArr.push(key + '=' + value);
    }

    return tempArr.join('&');
};
/**
 * 跳转到指定page
 */

const redirecToPage = (pageUrl, param, callback) => {
    if (param) {
        pageUrl = pageUrl + '?' + jsonToUrlParams(param);
    }

    uni.redirectTo({
        url: pageUrl,
        success: callback ? callback(true) : undefined,
        fail: callback ? callback(false) : undefined
    });
};
/**
 * 页面滚动到顶部
 */

const pageScrollToTop = (e) => {
    if (uni.pageScrollTo) {
        uni.pageScrollTo({
            scrollTop: 0
        });
    } else {
        MsgBox.alert('提示', '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试');
    }
};
/********************登录 注册 微信用户相关API封装***********************/

/**
 * 解决异步并发微信小程序Login请求JWT问题
 */

const WxLoginUtil = {
    wxLoginP: null,
    _Login: (noMsg) => {
        return new Promise((resolve, reject) => {
            if (!noMsg) {
                MsgBox.loading('登录中...');
            }

            uni.login({
                success: (res) => {
                    code2session(res.code)
                        .then((data) => {
                            log('wx login success');

                            if (!noMsg) {
                                MsgBox.success('登录成功', 1000);
                            }

                            if (resolve) {
                                resolve(data);
                            }
                        })
                        .catch((data) => {
                            log('wx login fail');
                            MsgBox.alert('系统异常,无法登录');

                            if (reject) {
                                reject();
                            }
                        });
                },
                fail: () => {
                    MsgBox.alert('微信服务器异常');
                }
            });
        });
    },

    /**
     * 调用微信登录
     */
    login: (noMsg) => {
        //判断当前存在就直接返回
        if (WxLoginUtil.wxLoginP) {
            return WxLoginUtil.wxLoginP;
        }

        clearJwt(); //首次赋值

        WxLoginUtil.wxLoginP = WxLoginUtil._Login(noMsg)
            .then(
                () => {
                    //执行完 就清空对象
                    WxLoginUtil.wxLoginP = null;
                },
                () => {
                    //执行完 就清空对象
                    WxLoginUtil.wxLoginP = null;
                }
            )
            .catch(() => {
                //异常 就清空对象
                WxLoginUtil.wxLoginP = null;
            });
        return WxLoginUtil.wxLoginP;
    }
};
/**
 * code转session
 */

const code2session = (code) => {
    return apiPost({
        url: JBOLT_APIS.wechat.login,
        data: {
            code: code
        }
    });
};
/**
 * 刷新jwt专用
 */

const JwtRefreshUtil = {
    refreshP: null,
    _Refresh: () => {
        return new Promise((resolve, reject) => {
            refreshJwt()
                .then((data) => {
                    log('refresh jwt success');

                    if (resolve) {
                        resolve(data);
                    }
                })
                .catch((data) => {
                    log('refresh jwt fail');
                    MsgBox.alert('系统异常,无法登录');

                    if (reject) {
                        reject();
                    }
                });
        });
    },

    /**
     * 调用刷新
     */
    refresh: () => {
        //判断当前存在就直接返回
        if (JwtRefreshUtil.refreshP) {
            return JwtRefreshUtil.refreshP;
        } //首次赋值

        JwtRefreshUtil.refreshP = JwtRefreshUtil._Refresh()
            .then(
                () => {
                    //执行完 就清空对象
                    JwtRefreshUtil.refreshP = null;
                },
                () => {
                    //执行完 就清空对象
                    JwtRefreshUtil.refreshP = null;
                }
            )
            .catch(() => {
                //异常 就清空对象
                JwtRefreshUtil.refreshP = null;
            });
        return JwtRefreshUtil.refreshP;
    }
};
/**
 * 执行刷新jwt
 */

const refreshJwt = () => {
    return apiGet({
        url: JBOLT_APIS.wechat.refreshJwt
    });
};
/**
 * 解密user信息
 */

const decryptUserInfo = (
    data = {
        rawData,
        signature,
        encryptedData,
        iv
    }
) => {
    return apiPost({
        url: JBOLT_APIS.wechat.decryptUserInfo,
        data: data
    });
};
/**
 * 手机号授权获取并解密
 */

const decryptPhoneNumber = (
    data = {
        rawData,
        signature,
        encryptedData,
        iv
    }
) => {
    return apiPost({
        url: JBOLT_APIS.wechat.decryptPhoneNumber,
        data: data
    });
};
/**
 * 绑定其他用户信息
 * @param {类型} type
 * @param {数据} data
 */

const bindOtherUser = (type, data) => {
    data.type = type;

    if (data.password) {
        data.password = processPwd(data.password);
    }

    return apiPost({
        url: JBOLT_APIS.wechat.bindOtherUser,
        data: data
    });
};
/**
 * 使用系统用户登录
 * @param {类型} type
 * @param {数据} data
 */

const loginSystemUser = (data) => {
    if (data.password) {
        data.password = processPwd(data.password);
    }

    return apiPost({
        url: JBOLT_APIS.wechat.loginSystemUser,
        data: data
    });
};
/**
 * 绑定系统jb_user用户信息
 * @param {绑定数据} data
 */

const bindSystemUser = (data) => {
    return bindOtherUser(JBOLT_APIS.wechat.bindUserType.SYSTEM_USER, data);
};
/**
 * 获取用户信息
 * @param {回调处理} callback
 * @param {提示描述信息} desc
 */

const getUserProfile = (callback, desc) => {
    uni.getUserProfile({
        desc: desc ? desc : '用于完善用户资料',
        success: (res) => {
            if (callback) {
                uni.checkSession({
                    success: (para) => {
                        callback(res);
                    },
                    fail: () => {
                        WxLoginUtil.login().then((para) => {
                            callback(res);
                        });
                    }
                });
            }
        }
    });
};

module.exports = {
    init: init,
    API: JBOLT_APIS,
    MsgBox: MsgBox,
    log: log,
    apiGet: apiGet,
    apiPost: apiPost,
    apiPostJson: apiPostJson,
    apiDelete: apiDelete,
    apiPut: apiPut,
    uploadFile: uploadFile,
    getApiUrl: getApiUrl,
    isLogined: isLogined,
    pageScrollToTop: pageScrollToTop,
    WxLoginUtil: WxLoginUtil,
    decryptUserInfo: decryptUserInfo,
    decryptPhoneNumber: decryptPhoneNumber,
    bindOtherUser: bindOtherUser,
    bindSystemUser: bindSystemUser,
    loginSystemUser: loginSystemUser,
    openPage: openPage,
    redirecToPage: redirecToPage,
    jsonToUrlParams: jsonToUrlParams,
    getUserProfile: getUserProfile,
    processPwd: processPwd
};
